<template>
    <div>
        <el-button type="danger" @click="addCategory">新增分类</el-button>
        <el-table :data="filterTableData" style="width: 100%">
            <el-table-column label="封面" prop="cover" width="110">
                <template v-slot:default="scope">
                    <Cover :cover="scope.row.cover"></Cover>
                </template>
            </el-table-column>
            <el-table-column label="名称" prop="categoryName" width="140"/>
            <el-table-column label="简介" prop="categoryDesc"/>
            <el-table-column label="博客数量" prop="blogCount" width="80"/>
            <el-table-column label="操作" width="150">
                <template #header>
                    <el-input v-model="search" size="small" placeholder="Type to search" class="search-input"/>
                </template>
                <template v-slot="{ row }">
                    <el-button size="small" @click="handleEdit(row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 编辑按钮点击后的弹窗-->
        <el-dialog v-model="dialogVisible" title="修改分类" width="30%" draggable>
            <!-- 第一个段落 -->
            <!-- <el-input v-model="rowData.cover" placeholder="封面" style="margin-bottom: 10px; height: 30px; font-size: 16px;" /> -->
            <CoverUpload v-model="rowData.cover" @update:filename="onFilenameUpdate"></CoverUpload>
            <!-- 第二个段落 -->
            <el-input v-model="rowData.categoryName" placeholder="名称"
                      style="margin-bottom: 10px; height: 30px; font-size: 16px;"/>

            <!-- 第三个段落 -->
            <el-input v-model="rowData.categoryDesc" placeholder="简介" class="multiline-input" type="textarea"
                      :autosize="{ minRows: 4, maxRows: 4 }" :maxlength="300" style="margin-bottom: 10px;"/>

            <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </span>
            </template>
        </el-dialog>
        <!-- 新增按钮点击后的弹窗-->
        <el-dialog v-model="dialogVisible2" title="修改分类" width="30%" draggable>
            <!-- 第一个段落 -->
            <!-- <el-input v-model="rowData.cover" placeholder="封面" style="margin-bottom: 10px; height: 30px; font-size: 16px;" /> -->
            <CoverUpload v-model="rowData.cover" @update:filename="onFilenameUpdate"></CoverUpload>
            <!-- 第二个段落 -->
            <el-input v-model="rowData.categoryName" placeholder="名称"
                      style="margin-bottom: 10px; height: 30px; font-size: 16px;"/>

            <!-- 第三个段落 -->
            <el-input v-model="rowData.categoryDesc" placeholder="简介" class="multiline-input" type="textarea"
                      :autosize="{ minRows: 4, maxRows: 4 }" :maxlength="300" style="margin-bottom: 10px;"/>

            <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave2">保存</el-button>
        </span>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
    import {ref, computed} from 'vue'
    import axios from 'axios'

    const rowData = ref({
        cover: '',
        categoryName: '',
        categoryDesc: ''
    })
    const savedData = ref([]);
    const dialogVisible = ref(false)
    const dialogVisible2 = ref(false)
    const tableData = ref([])
    const jwtToken = localStorage.getItem('jwtToken');

    const axiosInstance = axios.create({
        headers: {
            'Token': jwtToken // 将JWT令牌放入请求头的token字段
        }
    });
    const tableDataData = computed(() =>
        tableData.filter(
            (data) =>
                !(ref('')).value ||
                data.categoryName.toLowerCase().includes((ref('')).value.toLowerCase())
        )
    )
    // 发起请求并将数据赋值给tableData展示表格数据
    axiosInstance.get('http://localhost:8080/show')
        .then(response => {
            const responseData = response.data;
            if (Array.isArray(responseData.data) && responseData.data.length > 0) {
                tableData.value = responseData.data; // 赋值给tableData
            }
        })
        .catch(error => {
            console.error('请求失败:', error);
        });
    const search = ref('')
    const filterTableData = computed(() =>
        tableData.value.filter(
            (data) =>
                !search.value ||  // 修改这里
                data.categoryName.toLowerCase().includes(search.value.toLowerCase()) // 修改这里
        )
    )
    const handleEdit = (row) => {
        // 复制选定行的数据到 rowData
        rowData.value = {...row};
        dialogVisible.value = true;
        console.log(rowData.value)
    };
    const handleSave = () => {
        // 将编辑后的数据添加到 savedData 中
        savedData.value.push({...rowData.value});
        console.log(rowData.value)
        dialogVisible.value = false;
        const onFilenameUpdate = (filename) => {
            // 在这里获取到新的 filename
            console.log('New filename:', filename);
            rowData.cover = filename;
            // 更新 form.cover 或执行其他操作
        }
// 发起请求并将数据赋值给tableData展示表格数据
        axiosInstance.put('http://localhost:8080/update', rowData.value)
            .then(response => {
                const responseData = response.data;
                console.log(responseData.data);
                alert("保存成功")
                // 刷新页面
                location.reload();
                // 其他处理逻辑
            })
            .catch(error => {
                console.error('请求失败:', error);
            });
    }
    // 删除按钮点击时执行的逻辑
    const handleDelete = (row) => {
        // 在这里执行删除按钮的逻辑
        // row 参数可以用于获取相关数据
        console.log("删除按钮点击，处理删除逻辑，当前行数据：", row.categoryName);
        axiosInstance.delete(`http://localhost:8080/delete/${row.categoryName}`)
            .then(response => {
                // 处理删除成功的逻辑
                alert("删除成功")
                location.reload();

            })
            .catch(error => {
                // 处理删除失败的逻辑
            });
    };
    const addCategory = () => {
        dialogVisible2.value = true;

    }
    const handleSave2 = () => {
         axiosInstance.post('http://localhost:8080/addCategory', rowData.value)
            .then(response => {
                const responseData = response.data;
                console.log(responseData.data);
                alert("新建成功")
                // 刷新页面
                location.reload();
                // 其他处理逻辑
            })
            .catch(error => {
                console.error('请求失败:', error);
            });
    }
</script>

<style lang="scss">
    .multiline-input {
        margin-bottom: 10px;
        height: 120px;
        font-size: 16px;
        white-space: pre-wrap; /* 允许文本多行显示 */
        overflow-wrap: break-word; /* 在需要时自动换行 */
        resize: vertical; /* 垂直方向可以调整大小 */
        text-align: left; /* 文本从左上角开始显示 */
    }
</style>